package com.example.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.base.exception.CustomException;
import com.example.base.response.Result;
import com.example.entity.Good;
import com.example.entity.Params;

import com.example.service.GoodService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(tags = "商品信息管理")
@CrossOrigin
@RestController
@RequestMapping("/good")
public class GoodController {
    @Autowired
    private GoodService goodService;


    @GetMapping("/finder")
    public Result findAll() {
        return Result.success(goodService.findAll());
    }


    @PostMapping
    public Result save(@RequestBody Good good) {
        if (good.getId() == null) {
            goodService.add(good);
        } else {
            goodService.update(good);
        }
        return Result.success();
    }

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Good> info = goodService.findBySearch(params);
        return Result.success(info);
    }

    @DeleteMapping("/{id}")

    public Result delete(@PathVariable Integer id) {

        goodService.delete(id);
        return Result.success();
    }

    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        List<Good> all = goodService.findAll();
        if (CollectionUtil.isEmpty(all)) {
            throw new CustomException("未找到数据");
        }
        List<Map<String, Object>> list = new ArrayList<>((all.size()));
        for (Good good : all) {
            Map<String, Object> row = new HashMap<>();
            row.put("商品名称", good.getGoodname());
            row.put("商品描述", good.getPrice());
            row.put("供货商", good.getPlace());
            row.put("商品产地", good.getAddress());
            list.add(row);
        }
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=good.xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
        return Result.success();
    }


}
